<template>
    <div class="asset-inventory">
        <!-- 顶部导航栏 -->
        <van-nav-bar title="资产盘点" left-arrow @click-left="$router.back()" />

        <!-- 标签页 -->
    <!-- 修改模板 -->
<van-tabs v-model="activeTab" @change="handleTabChange" class="new-tabs-box" scrollable swipe-threshold="4" v-if="tabList && tabList.length">
    <van-tab v-for="(item, index) in tabList" :key="index" :title="item.name" :name="item.uniqueKey" />
</van-tabs>

        <!-- 表单内容区域 -->
        <div class="form-container">
            <template v-if="currentFormGroups && currentFormGroups.length">
                <template v-for="group in currentFormGroups">
                    <div class="group-title" style="color: #000; background-color: #f8faff">{{ group.name }}</div>
                    <van-cell-group class="form-group">
                        <!-- 普通输入字段 -->
                        <van-field
                            v-for="(item, index) in group.fields"
                            :value="getDisplayValue(item)"
                            :name="item.code"
                            :key="`${group.id}-${item.id}-${index}`"
                            :label="item.name"
                            :placeholder="`请输入${item.name}`"
                            :required="item.required === 1"
                            @input="handleInput(getKey(item), $event, item)"
                            :type="getFieldType(item)"
                        />

                        <!-- 日期选择字段 -->
                        <van-field
                            v-for="item in group.dateFields"
                            :key="item.id"
                            :name="item.code"
                            :label="item.name"
                            :value="getDisplayValue(item)"
                            :placeholder="`请选择${item.name}`"
                            :required="item.required === 1"
                            is-link
                            @click="
                                showDatePicker = true
                                currentDateField = getKey(item)
                            "
                        />

                        <!-- 本地选择字段（使用 van-picker） -->
                        <van-field v-for="item in group.localSelectFields" :key="item.id" :name="item.code" :label="item.name" :placeholder="`请选择${item.name}`" :required="item.required === 1" is-link :value="getSelectText(item)" @click="handleLocalSelect(item)" />

                        <!-- 远程选择字段（跳转到其他页面选择） -->
                        <van-field v-for="item in group.remoteSelectFields" :key="item.id" :name="item.code" :label="item.name" :placeholder="`请选择${item.name}`" :required="item.required === 1" is-link :value="getSelectText(item)" @click="handleRemoteSelect(item)" />

                        <!-- 说明备注字段 -->
                        <van-field
                            v-for="item in group.RemarkFields"
                            :key="item.id"
                            :name="item.code"
                            :label="item.name"
                            rows="2"
                            type="textarea"
                            maxlength="50"
                            :placeholder="`请输入${item.name}`"
                            :required="item.required === 1"
                            :value="getDisplayValue(item)"
                            @input="handleInput(getKey(item), $event, item)"
                        />

                        <!-- 图片上传字段 -->
                        <div v-for="item in group.imageFields" :key="item.id" class="image-upload-group">
                            <div class="image-upload-label">
                                <span>{{ item.name }}</span>
                                <span v-if="item.required === 1" class="required">*</span>
                            </div>
                            <div class="image-upload-container">
                                <upload-file :attachment-list="formData[getKey(item)]" :edit-able="true" @uploadFileComplete="handleUploadComplete(getKey(item), $event)" @deleteFile="handleDeleteFile(getKey(item), $event)" />
                                <div class="upload-count">{{ (formData[getKey(item)] && formData[getKey(item)].length) || 0 }}/10</div>
                            </div>
                        </div>
                    </van-cell-group>
                </template>
            </template>

            <template v-else>
                <van-empty description="暂无表单数据" />
            </template>
        </div>

        <!-- 底部操作按钮 -->
        <div class="bottom-actions">
            <van-button round style="background-color: #3772ff; color: #fff" @click="handleSave">保存</van-button>
        </div>

        <!-- 日期选择器弹窗 -->
        <van-popup v-model="showDatePicker" position="bottom">
            <van-datetime-picker v-model="currentDateValue" type="date" :show-toolbar="true" @confirm="handleDateConfirm" @cancel="showDatePicker = false" />
        </van-popup>

        <!-- 本地选择器弹窗 -->
        <van-popup v-model="showLocalSelector" position="bottom">
            <van-picker v-model="currentLocalSelectValue" :show-toolbar="true" :columns="getLocalSelectOptions(currentSelectField)" @confirm="handleLocalSelectConfirm" @cancel="showLocalSelector = false" />
        </van-popup>
    </div>
</template>

<script>
import backMixin from '../../mixins/backMixin'
import UploadFile from '../../components/uploadFile.vue'

export default {
    mixins: [backMixin],
    components: { UploadFile },

    data() {
        return {
            // 标签页相关
            activeTab: '',
            tabList: [],

            // 表单数据
            formData: {},
            currentFormGroups: [],

            // 弹窗状态
            showDatePicker: false,
            showLocalSelector: false,
            currentDateField: '',
            currentDateValue: new Date(),
            currentSelectField: null,
            currentLocalSelectValue: '',

            // 树结构数据
            allAssetData: [],
            orgTree: null,
            propertyTypeTree: null,
            projectTree: null,
            listTree: null,

            // 本地选择选项
            localSelectOptions: {
                rightState: [
                    { value: 1, text: '有证' },
                    { value: 0, text: '无证' },
                    { value: 2, text: '未知' }
                ],
                mortgaged: [
                    { value: 1, text: '是' },
                    { value: 0, text: '否' }
                ],
                planned: [
                    { value: 1, text: '是' },
                    { value: 0, text: '否' }
                ],
                onAccount: [
                    { value: 1, text: '是' },
                    { value: 0, text: '否' }
                ],
                provisional: [
                    { value: 1, text: '是' },
                    { value: 0, text: '否' }
                ],
                dilapidated: [
                    { value: 1, text: '是' },
                    { value: 0, text: '否' }
                ],
                accountSubject: [
                    { value: '固定资产', text: '固定资产' },
                    { value: '存货', text: '存货' }
                ],
                buildingStructure: [
                    { value: '钢结构', text: '钢结构' },
                    { value: '钢筋混凝土结构', text: '钢筋混凝土结构' },
                    { value: '混合结构', text: '混合结构' },
                    { value: '砖木结构', text: '砖木结构' }
                ],
                sourceId: [
                    { value: '自有', text: '自有' },
                    { value: '租赁', text: '租赁' },
                    { value: '购买', text: '购买' },
                    { value: '其他', text: '其他' }
                ]
            },

            // 远程选择字段
            remoteSelectFields: ['typeId', 'orgId', 'purposeIds', 'projectId', 'unitId', 'rightUnitId', 'streetId','coordinateAddress','address']
        }
    },

    activated() {
        this.handleBackDataFromRoute()
    },

    async created() {
        await this.loadAllTreeData()
        await this.getEditpropertyField()
    },

    mounted() {
        this.handleBackDataFromRoute()
    },

    methods: {
        async loadAllTreeData() {
            try {
                await Promise.all([this.getorgProjectTree(), this.getorgPropertyType(), this.getorgTree(), this.getlistTree()])
            } catch (error) {
                console.error('加载树结构数据失败:', error)
            }
        },
handleBackDataFromRoute() {
    console.log('处理返回数据')
    try {
        let backData = this.$store?.state?.assectData?.returnData
        console.log('回退数据:', backData)
        if (backData) {
            
            this.$store.commit('assectData/setReturnData', null)
            
            // 定义ID字段和对应名称字段的映射
            const idNameMap = {
                'orgId': 'orgName',
                'typeId': 'typeName', 
                'projectId': 'projectName',
                'unitId': 'unitName',
                'rightUnitId': 'rightUnitName',
                'streetId': 'streetName',
                'purposeIds': 'purposeNames',
                'rightTypeId': 'rightTypeName'
            }
            
            // 处理单个对象的情况
            if (backData && typeof backData === 'object' && !Array.isArray(backData)) {
                Object.keys(backData).forEach(key => {
                    const value = backData[key]
                    
                    // 如果是ID字段，设置ID值和对应的名称值
                    if (idNameMap[key]) {
                        const nameKey = idNameMap[key]
                        
                        // 设置ID值
                        if (value && typeof value === 'object') {
                            // 如果是对象，提取id/value
                            if (value.id !== undefined) {
                                this.$set(this.formData, key, value.id)
                            } else if (value.value !== undefined) {
                                this.$set(this.formData, key, value.value)
                            } else {
                                this.$set(this.formData, key, value)
                            }
                            
                            // 设置对应的名称值
                            if (value.name !== undefined) {
                                this.$set(this.formData, nameKey, value.name)
                            } else if (value.text !== undefined) {
                                this.$set(this.formData, nameKey, value.text)
                            } else if (backData[nameKey]) {
                                this.$set(this.formData, nameKey, backData[nameKey])
                            }
                        } else {
                            // 如果是简单值，直接设置
                            this.$set(this.formData, key, value)
                            
                            // 如果有对应的名称字段，也设置
                            if (backData[nameKey]) {
                                this.$set(this.formData, nameKey, backData[nameKey])
                            }
                        }
                    } 
                    // 如果是名称字段，且对应的ID字段已经设置，则设置名称字段
                    else if (Object.values(idNameMap).includes(key)) {
                        // 只有当对应的ID字段有值时，才设置名称字段
                        const idKey = Object.keys(idNameMap).find(k => idNameMap[k] === key)
                        if (idKey && this.formData[idKey]) {
                            this.$set(this.formData, key, value)
                        }
                    }
                    // 普通字段
                    else {
                        this.$set(this.formData, key, value)
                    }
                })
                
                // 第二次遍历，确保所有名称字段都被正确设置
                Object.keys(idNameMap).forEach(idKey => {
                    const nameKey = idNameMap[idKey]
                    // 如果ID字段有值但名称字段没有值，尝试从backData中获取
                    if (this.formData[idKey] && !this.formData[nameKey] && backData[nameKey]) {
                        this.$set(this.formData, nameKey, backData[nameKey])
                    }
                })
            }
            
            // 处理数组的情况
            else if (Array.isArray(backData)) {
                backData.forEach(item => {
                    if (item && typeof item === 'object') {
                        Object.keys(item).forEach(key => {
                            const value = item[key]
                            
                            // 如果是ID字段，设置ID值和对应的名称值
                            if (idNameMap[key]) {
                                const nameKey = idNameMap[key]
                                
                                // 设置ID值
                                if (value && typeof value === 'object') {
                                    if (value.id !== undefined) {
                                        this.$set(this.formData, key, value.id)
                                    } else if (value.value !== undefined) {
                                        this.$set(this.formData, key, value.value)
                                    }
                                    
                                    // 设置对应的名称值
                                    if (value.name !== undefined) {
                                        this.$set(this.formData, nameKey, value.name)
                                    } else if (value.text !== undefined) {
                                        this.$set(this.formData, nameKey, value.text)
                                    }
                                } else {
                                    this.$set(this.formData, key, value)
                                }
                            } 
                            // 普通字段
                            else {
                                this.$set(this.formData, key, value)
                            }
                        })
                    }
                })
            }

            this.$nextTick(() => {
                if (this.activeTab) {
                    this.handleTabChange(this.activeTab)
                }
                console.log('表单数据更新后:', this.formData)
                
                // 强制更新视图
                try {
                    this.$forceUpdate()
                } catch (e) {
                    console.log('强制更新失败:', e)
                }
            })
        }
    } catch (error) {
        console.error('处理回退数据出错:', error)
    }
},
// 获取显示字段的键名
getDisplayFieldKey(key) {
    if (!key) return ''
    
    // 常见的ID字段对应的显示字段映射
    const displayFieldMap = {
        'orgId': 'orgName',
        'typeId': 'typeName', 
        'projectId': 'projectName',
        'unitId': 'unitName',
        'rightUnitId': 'rightUnitName',
        'streetId': 'streetName',
        'purposeIds': 'purposeNames',
        'rightTypeId': 'rightTypeName',
        // 添加其他可能的映射
    }
    
    return displayFieldMap[key]
},
        async getEditpropertyField() {
            const id = this.$route.query.k
            let data = { propertyTypeId: id }
            let res = await this.$Geting(this.$api.getEditpropertyField, data)

            if (res.code === '0' && res.data) {
                this.initAssetData(res.data)
                this.getdetailData()
            } else {
                this.$toast(res.message)
            }
        },

        async getdetailData() {
            const id = this.$route.query.id
            let data = { id: id }
            let res = await this.$Geting(this.$api.getdetailById, data)

            if (res.code === '0' && res.data) {
                const business = res.data.businessDto || {}
                this.mapBusinessDataToForm(business)

                this.$nextTick(() => {
                    const currentTab = this.activeTab
                    this.handleTabChange(currentTab)
                })
            } else {
                this.$toast(res.message)
            }
        },

        // 核心方法
        initAssetData(data) {
            let meta = data
            if (data && !Array.isArray(data) && data.customizeList && Array.isArray(data.customizeList)) {
                meta = data.customizeList
            }

            if (!meta || !Array.isArray(meta)) {
                this.$toast('数据加载失败，请检查数据源')
                return
            }

            this.allAssetData = meta
            this.initTabs()
            this.initFormData()
        },
// 在 methods 中添加
generateUniqueTabKey(item) {
    if (!item) return '';
    const baseKey = item.code || item.fieldKey || '';
    return `${baseKey}_${item.id}`;
},

initTabs() {
    this.tabList = this.allAssetData
        .filter((item) => {
            return item && typeof item === 'object' && (item.code || item.fieldKey) && item.name;
        })
        .map((item) => {
            return {
                ...item,
                uniqueKey: this.generateUniqueTabKey(item)
            };
        });

    if (this.tabList.length) {
        this.activeTab = this.tabList[0].uniqueKey;
        this.handleTabChange(this.activeTab);
    }
},

handleTabChange(tabCode) {
    const tabItem = this.tabList.find((item) => item.uniqueKey === tabCode);
    
    if (!tabItem || !tabItem.childList) {
        this.currentFormGroups = [];
        return;
    }
    
    this.currentFormGroups = tabItem.childList
        .filter((group) => group && group.name)
        .map((group) => this.formatGroupData(group));
},

        initFormData() {
            const initField = (item) => {
                const key = this.getKey(item)
                if (!key) return

                const accept = (item.accept || '').toString().toLowerCase()
                const fileType = (item.fileType || '').toString().toLowerCase()
                const fileLike = item.fieldType === 'file' || item.fieldType === 'image' || item.type === 'file' || item.type === 'image' || item.code === 'zctp' || item.isImage === true || accept.indexOf('image') > -1 || fileType.indexOf('image') > -1

                if (fileLike) this.$set(this.formData, key, [])
                else if (this.formData[key] === undefined) this.$set(this.formData, key, '')
            }

            const recursiveInit = (items) => {
                if (!items || !Array.isArray(items)) return
                items.forEach((item) => {
                    if (item?.childList?.length) {
                        recursiveInit(item.childList)
                    } else if ((item?.fieldKey || item?.code) && item.fieldKey !== 'unrealized') {
                        if (item.fieldKey !== 'qrCode' && item.code !== 'qrCode') {
                            initField(item)
                        }
                    }
                })
            }

            recursiveInit(this.allAssetData)
        },


        // 字段分类和格式化
        formatGroupData(group) {
            const allFields = this.collectFields(group.childList)
            return {
                id: group.id,
                name: group.name,
                fields: allFields.filter((item) => this.isNormalField(item)),
                dateFields: allFields.filter((item) => this.isDateField(item)),
                localSelectFields: allFields.filter((item) => this.isLocalSelectField(item)),
                remoteSelectFields: allFields.filter((item) => this.isRemoteSelectField(item)),
                imageFields: allFields.filter((item) => this.isImageField(item)),
                RemarkFields: allFields.filter((item) => this.isRemarkData(item))
            }
        },

        collectFields(items) {
            let fields = []
            if (!items || !Array.isArray(items)) return fields

            items.forEach((item) => {
                if (item?.childList?.length) {
                    fields = [...fields, ...this.collectFields(item.childList)]
                } else if ((item?.fieldKey || item?.code) && item.fieldKey !== 'unrealized') {
                    if (item.fieldKey !== 'qrCode' && item.code !== 'qrCode') {
                        fields.push(item)
                    }
                }
            })
            return fields
        },

        // 字段类型判断
        isDateField(item) {
            if (!item) return false
            const key = item.fieldKey || item.code
            const dateKeys = ['acquireDate', 'postDate', 'issuedDate', 'mortgageBeginDate', 'mortgageEndDate', 'builtYear']
            return item.fieldType === 'date' || item.type === 'date' || item.inputType === 'date' || dateKeys.includes(key)
        },

        isRemarkData(item) {
            if (!item) return false
            const key = item.fieldKey || item.code
            return item.fieldType === 'textarea' || item.type === 'textarea' || item.inputType === 'textarea' || key === 'remark'
        },

        isSelectField(item) {
            if (!item) return false
            const key = item.fieldKey || item.code
            const selectKeys = ['typeId', 'orgId', 'purposeIds', 'projectId', 'sourceId', 'unitId', 'rightState', 'rightUnitId', 'rightTypeId','coordinateAddress','streetId', 'address','mortgaged', 'planned', 'onAccount', 'accountSubject', 'buildingStructure']
            const hasOptions = Array.isArray(item.options) || Array.isArray(item.dictList) || Array.isArray(item.columns)
            return item.fieldType === 'select' || item.type === 'select' || item.inputType === 'select' || hasOptions || selectKeys.includes(key)
        },

        isImageField(item) {
            if (!item) return false
            const key = item.fieldKey || item.code
            const accept = (item.accept || '').toString().toLowerCase()
            const fileType = (item.fileType || '').toString().toLowerCase()
            return item.fieldType === 'image' || item.type === 'image' || item.inputType === 'image' || key === 'zctp_unrealized' || item.isImage === true || accept.indexOf('image') > -1 || fileType.indexOf('image') > -1
        },

        isNormalField(item) {
            if (!item) return false
            return !(this.isDateField(item) || this.isSelectField(item) || this.isImageField(item) || this.isRemarkData(item))
        },

        // 选择字段处理
        isLocalSelectField(item) {
            if (!item) return false
            const key = this.getKey(item)
            return Object.keys(this.localSelectOptions).includes(key)
        },

        isRemoteSelectField(item) {
            if (!item) return false
            const key = this.getKey(item)
            return this.remoteSelectFields.includes(key)
        },

        getLocalSelectOptions(field) {
            if (!field) return []
            const key = this.getKey(field)
            return this.localSelectOptions[key] || []
        },

       getRemoteSelectOptions(field) {
    if (!field) return []
    const key = this.getKey(field)

    switch (key) {
        case 'projectId':
            return this.formatTreeToOptions(this.projectTree)
        case 'orgId':
            return this.formatTreeToOptions(this.orgTree)
        case 'typeId':
            return this.formatTreeToOptions(this.propertyTypeTree)
        case 'purposeIds':
            return this.formatTreeToOptions(this.listTree)
        default:
            const source = field || {}
            const rawList = source.options || source.dictList || source.columns || source.items || []
            if (Array.isArray(rawList) && rawList.length) {
                return rawList.map((i) => {
                    if (typeof i === 'object') {
                        // 确保选项对象有 value 和 text 属性
                        const value = i.value ?? i.id ?? i.key ?? i
                        const text = i.text ?? i.name ?? i.label ?? i.title ?? String(value)
                        return { value, text }
                    }
                    return { value: i, text: String(i) }
                })
            }
            return []
    }
},

       formatTreeToOptions(treeData) {
    if (!treeData) return []

    const options = []
    const traverse = (node) => {
        if (!node) return

        if (node.nodeId || node.id) {
            const value = node.nodeId || node.id
            const text = node.nodeName || node.name || node.text || String(value)
            options.push({ value, text })
        }

        if (node.childList && Array.isArray(node.childList)) {
            node.childList.forEach((child) => traverse(child))
        }
        if (node.children && Array.isArray(node.children)) {
            node.children.forEach((child) => traverse(child))
        }
    }

    if (Array.isArray(treeData)) {
        treeData.forEach((node) => traverse(node))
    } else {
        traverse(treeData)
    }

    return options
},
        // 选择器操作
        handleLocalSelect(item) {
            this.showLocalSelector = true
            this.currentSelectField = item
            const key = this.getKey(item)
            this.currentLocalSelectValue = this.formData[key] || ''
        },

    handleLocalSelectConfirm(value) {
    if (!this.currentSelectField) {
        this.showLocalSelector = false
        return
    }

    const key = this.getKey(this.currentSelectField)
    if (!key) {
        this.showLocalSelector = false
        return
    }

    // 确保存储的是基本类型值
    this.$set(this.formData, key, value)
    this.showLocalSelector = false
},

        handleRemoteSelect(item) {
            const codeActions = {
                xmdz: () => this.$router.push({ name: 'assectLocation' }),
                xmjddz: () => this.$router.push({ name: 'assectLocation' }),
                xmxxdz: () => this.$router.push({ name: 'assectLocation' }),
                zclx: () => this.$router.push({ name: 'assectType', params: { key: 'zclx' }, query: { returnName: this.$route.name } }),
                ssxm: () => this.$router.push({ name: 'assectType', params: { key: 'ssxm' }, query: { returnName: this.$route.name } }),
                gldw: () => this.$router.push({ name: 'assectType', params: { key: 'gldw' }, query: { returnName: this.$route.name } }),
                zcyt: () => this.$router.push({ name: 'assectType', params: { key: 'zcyt' }, query: { returnName: this.$route.name } }),
                glzc: () => this.$router.push({ name: 'assetCorrelation', params: { key: 'glzc' } }),
                yjdw: () => this.$router.push({ name: 'selectUnit', params: { key: 'yjdw' } }),
                cqdw: () => this.$router.push({ name: 'selectUnit', params: { key: 'cqdw' } }),
                dyqr: () => this.$router.push({ name: 'selectUnit', params: { key: 'dyqr' } })
            }

            if (codeActions[item.code]) {
                codeActions[item.code]()
            } else {
                this.$router.push({
                    name: 'assectType',
                    params: { key: item.code },
                    query: { returnName: this.$route.name }
                })
            }
        },

        // 数据映射
        mapBusinessDataToForm(businessDto) {
            if (!businessDto || !this.allAssetData) return

            const flatData = this.flattenBusinessData(businessDto)
            const fields = this.collectFields(this.allAssetData)

            fields.forEach((item) => {
                const key = this.getKey(item)
                if (!key) return

                let val = flatData[key]
                if (val !== undefined && val !== null) {
                    this.$set(this.formData, key, val)
                }
            })

            this.manualMapSpecialFields(businessDto)
        },

        flattenBusinessData(businessDto) {
            const result = {}

            const flatten = (obj, prefix = '') => {
                if (!obj || typeof obj !== 'object') return

                Object.keys(obj).forEach((key) => {
                    const value = obj[key]
                    const fullKey = prefix ? `${prefix}.${key}` : key

                    if (value && typeof value === 'object' && !Array.isArray(value)) {
                        flatten(value, fullKey)
                    } else {
                        result[fullKey] = value
                        if (prefix && !result[key]) {
                            result[key] = value
                        }
                    }
                })
            }

            flatten(businessDto)
            return result
        },

      // 在 mapBusinessDataToForm 方法中完善反向映射
manualMapSpecialFields(businessDto) {
    if (!businessDto) return

    // 映射主要字段
    if (businessDto.projectId) this.$set(this.formData, 'projectId', businessDto.projectId)
    if (businessDto.orgId) this.$set(this.formData, 'orgId', businessDto.orgId)
    if (businessDto.typeId) this.$set(this.formData, 'typeId', businessDto.typeId)
    if (businessDto.purposeIds) this.$set(this.formData, 'purposeIds', businessDto.purposeIds)

    // 映射嵌套字段 - 与 convertToBusinessDtoFormat 方法对应
    if (businessDto.acceptWebDto) {
        const accept = businessDto.acceptWebDto
        if (accept.sourceId !== undefined) this.$set(this.formData, 'sourceId', accept.sourceId)
        if (accept.acquireDate !== undefined) this.$set(this.formData, 'acquireDate', accept.acquireDate)
        if (accept.unitId !== undefined) this.$set(this.formData, 'unitId', accept.unitId)
    }

    if (businessDto.valueWebDto) {
        const value = businessDto.valueWebDto
        if (value.price !== undefined) this.$set(this.formData, 'price', value.price)
        if (value.unitPrice !== undefined) this.$set(this.formData, 'unitPrice', value.unitPrice)
        if (value.postDate !== undefined) this.$set(this.formData, 'postDate', value.postDate)
        if (value.onAccount !== undefined) this.$set(this.formData, 'onAccount', value.onAccount)
        if (value.accountSubject !== undefined) this.$set(this.formData, 'accountSubject', value.accountSubject)
    }

    if (businessDto.landDetailWebDto) {
        const land = businessDto.landDetailWebDto
        if (land.landArea !== undefined) this.$set(this.formData, 'landArea', land.landArea)

        if (land.certificateWebDto) {
            const cert = land.certificateWebDto
            if (cert.rightState !== undefined) this.$set(this.formData, 'rightState', cert.rightState)
            if (cert.rightUnitId !== undefined) this.$set(this.formData, 'rightUnitId', cert.rightUnitId)
            if (cert.rightRatio !== undefined) this.$set(this.formData, 'rightRatio', cert.rightRatio)
            if (cert.issuedDate !== undefined) this.$set(this.formData, 'issuedDate', cert.issuedDate)
            if (cert.mortgaged !== undefined) this.$set(this.formData, 'mortgaged', cert.mortgaged)
        }

        if (land.operateWebDto) {
            const operate = land.operateWebDto
            if (operate.planned !== undefined) this.$set(this.formData, 'planned', operate.planned)
        }
    }

    // 映射附件数据
    if (businessDto.attachmentWebDtoList && Array.isArray(businessDto.attachmentWebDtoList)) {
        // 这里需要根据业务逻辑将附件分配到对应的字段
        // 暂时简单处理，将所有附件放到第一个图片字段
        const imageFields = this.getAllImageFields();
        if (imageFields.length > 0) {
            const firstImageField = imageFields[0];
            const key = this.getKey(firstImageField);
            if (key) {
                this.$set(this.formData, key, businessDto.attachmentWebDtoList);
            }
        }
    }
},

        // 工具方法
        getFieldType(item) {
            if (!item) return 'text'
            if (item.fieldType === 'number' || item.type === 'number' || item.inputType === 'number') return 'number'
            const numberKeys = ['countAmount', 'price', 'unitPrice', 'originalPrice', 'mortgageAmount', 'creditAmount', 'rightRatio']
            const key = item.fieldKey || item.code
            if (numberKeys.includes(key)) return 'number'
            return 'text'
        },

        handleInput(field, value, item) {
            if (!field) return

            if (item && (item.fieldType === 'number' || item.type === 'number' || item.inputType === 'number')) {
                const num = Number(value)
                this.$set(this.formData, field, Number.isNaN(num) ? value : num)
                return
            }

            this.$set(this.formData, field, value)
        },

  getDisplayValue(item) {
    if (!item) return ''
    const key = this.getKey(item)
    const val = this.formData[key]
    if (val === undefined || val === null) return ''

    // 如果是选择字段，使用 getSelectText 来显示
    if (this.isSelectField(item)) {
        return this.getSelectText(item)
    }

    if (Array.isArray(val)) {
        try {
            const opts = this.getSelectOptions(item) || []
            const texts = val.map((v) => {
                const found = opts.find((o) => o && (o.value === v || String(o.value) === String(v) || o.text === v))
                return found ? found.text ?? String(found.value) : String(v)
            })
            return texts.join(',')
        } catch (e) {
            return val.join(',')
        }
    }

    if (typeof val === 'object') {
        const text = val.name || val.label || val.text || val.title || val.value
        return text !== undefined ? String(text) : JSON.stringify(val)
    }

    return String(val)
},
getSelectText(field) {
    if (!field) return ''
    const key = this.getKey(field)
    let val = this.formData[key]
    if (!val && val !== 0) return ''

    // 首先检查是否有对应的显示字段
    const displayKey = this.getDisplayFieldKey(key)
    const displayValue = this.formData[displayKey]
    if (displayValue) {
        return String(displayValue)
    }

    // 如果值本身就是对象，尝试从中提取显示文本
    if (val && typeof val === 'object') {
        // 尝试从对象中提取显示文本
        if (val.name !== undefined) {
            return String(val.name)
        } else if (val.text !== undefined) {
            return String(val.text)
        } else if (val.label !== undefined) {
            return String(val.label)
        }
        // 如果无法提取显示文本，再尝试提取值
        else if (val.value !== undefined) {
            val = val.value
        } else if (val.id !== undefined) {
            val = val.id
        } else {
            // 如果既没有显示文本也没有值，返回空
            return ''
        }
    }

    // 如果是数组，处理数组中的每个元素
    if (Array.isArray(val)) {
        const texts = val.map((v) => {
            // 处理数组中的对象值
            let actualValue = v
            if (v && typeof v === 'object') {
                // 优先提取显示文本
                if (v.name !== undefined) return String(v.name)
                if (v.text !== undefined) return String(v.text)
                if (v.label !== undefined) return String(v.label)
                // 没有显示文本则提取值
                if (v.value !== undefined) actualValue = v.value
                else if (v.id !== undefined) actualValue = v.id
            }
            
            // 通过选项查找显示文本
            const options = this.getSelectOptions(field)
            const found = options.find((o) => o && (o.value === actualValue || String(o.value) === String(actualValue)))
            return found ? found.text : String(actualValue)
        })
        return texts.join(',')
    }

    // 如果是单个值，通过选项查找显示文本
    const options = this.getSelectOptions(field)
    const found = options.find((o) => o && (o.value === val || String(o.value) === String(val)))
    return found ? found.text : String(val)
},

        getSelectOptions(field) {
            if (!field) return []

            if (this.isLocalSelectField(field)) {
                return this.getLocalSelectOptions(field)
            }

            if (this.isRemoteSelectField(field)) {
                return this.getRemoteSelectOptions(field)
            }

            const source = field || {}
            const rawList = source.options || source.dictList || source.columns || source.items || []
            if (Array.isArray(rawList) && rawList.length) {
                return rawList.map((i) => {
                    if (typeof i === 'object')
                        return {
                            value: i.value ?? i.id ?? i.key ?? i,
                            text: i.text ?? i.name ?? i.label ?? i.title ?? i
                        }
                    return { value: i, text: i }
                })
            }

            return []
        },

        handleDateConfirm(date) {
            if (this.currentDateField) {
                this.formData[this.currentDateField] = this.formatDate(date)
            }
            this.showDatePicker = false
        },

        formatDate(date) {
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            return `${year}-${month}-${day}`
        },

        getKey(item) {
            if (!item) return ''
            return item.fieldKey || item.code || ''
        },

        // API 调用
        async getorgProjectTree() {
            try {
                const res = await this.$Geting(this.$api.getorgProjectTree)
                if (res.code === '0') {
                    this.projectTree = res.data.treeData
                    this.$store.commit('assectData/setProjectTree', this.projectTree)
                } else {
                    this.$toast(res.message)
                }
            } catch (err) {
                console.error('获取项目树出错', err)
            }
        },

        async getorgPropertyType() {
            try {
                const res = await this.$Geting(this.$api.getorgPropertyType)
                if (res.code === '0') {
                    this.propertyTypeTree = res.data
                      this.$store.commit('assectData/setpropertyTypeTree', this.propertyTypeTree)
                } else {
                    this.$toast(res.message)
                }
            } catch (err) {
                console.error('获取资产类型树出错', err)
            }
        },

        async getorgTree() {
            try {
                const res = await this.$Geting(this.$api.getorgTree)
                if (res.code === '0') {
                    this.orgTree = res.data.treeData
                    this.$store.commit('assectData/setorgTree', this.orgTree)
                } else {
                    this.$toast(res.message)
                }
            } catch (err) {
                console.error('获取管理单位树出错', err)
            }
        },

        async getlistTree() {
            try {
                const res = await this.$Posting(this.$api.getlistTree)
                if (res.code === '0') {
                    this.listTree = res.data
                     this.$store.commit('assectData/setlistTree', this.listTree)
                } else {
                    this.$toast(res.message)
                }
            } catch (err) {
                console.error('获取资产用途树出错', err)
            }
        },


// 新增方法：获取所有图片字段
getAllImageFields() {
    const imageFields = [];
    const traverse = (items) => {
        if (!items || !Array.isArray(items)) return;
        items.forEach(item => {
            if (item.childList) {
                traverse(item.childList);
            } else if (this.isImageField(item)) {
                imageFields.push(item);
            }
        });
    };
    traverse(this.allAssetData);
    return imageFields;
},
        async handleSave() {
    try {
        // 将扁平数据转换为后端需要的嵌套格式
        const submitData = {
            action: 3,//信息变更
                stocktakingResult:0,//待盘点
                taskId: this.$route.query.id,
taskPropertyId: this.$route.query.taskPropertyId || '', 
            stocktakingDto: {
                ...this.convertToBusinessDtoFormat().businessDto,
                
            },
        }
        
        console.log('提交保存数据:', submitData);
        const res = await this.$Posting(this.$api.stocktaking, submitData)
        
        if (res && (res.code === '0' || res.isSuccess === true)) {
            this.$toast.success('保存成功')
        } else {
            this.$toast(res?.message || '保存失败')
        }
    } catch (err) {
        console.error('提交保存出错', err)
        this.$toast('保存失败')
    }
},

// 新增方法：将扁平数据转换为后端需要的嵌套格式
convertToBusinessDtoFormat() {
    const formData = this.formData;
    
    // 构建 businessDto 主体
    const businessDto = {
        id: this.$route.query.id || '', // 从路由参数获取id
        name: formData.name || '',
        code: formData.code || '',
        orgId: formData.orgId || '',
        projectId: formData.projectId || '',
        typeId: formData.typeId || '',
        purposeIds: formData.purposeIds || '',
        remark: formData.remark || '',
        longitude: formData.longitude || '',
        latitude: formData.latitude || '',
        coordinateAddress: formData.coordinateAddress || '',
        address: formData.address || '',
        streetId: formData.streetId || '',
        countAmount: formData.countAmount || null,
        // 其他直接字段...
    };

    // 构建 acceptWebDto
    const acceptWebDto = {
        sourceId: formData.sourceId || null,
        acquireDate: formData.acquireDate || null,
        unitId: formData.unitId || null
    };

    // 构建 valueWebDto
    const valueWebDto = {
        price: formData.price || null,
        unitPrice: formData.unitPrice || null,
        postDate: formData.postDate || null,
        onAccount: formData.onAccount || null,
        accountSubject: formData.accountSubject || null
    };

    // 构建 landDetailWebDto
    const landDetailWebDto = {
        landArea: formData.landArea || null,
        certificateWebDto: {
            rightState: formData.rightState || 0,
            rightUnitId: formData.rightUnitId || null,
            rightRatio: formData.rightRatio || null,
            issuedDate: formData.issuedDate || null,
            mortgaged: formData.mortgaged || 0
        },
        operateWebDto: {
            planned: formData.planned || 0
        }
    };

    // 处理附件数据
    const attachmentWebDtoList = [];
    
    // 收集所有图片字段的附件
    Object.keys(formData).forEach(key => {
        const value = formData[key];
        if (Array.isArray(value) && value.length > 0 && 
            (typeof value[0] === 'object' && (value[0].fileUrl || value[0].token))) {
            // 这是附件数据
            value.forEach(fileItem => {
                attachmentWebDtoList.push({
                    fileUrl: fileItem.fileUrl || fileItem.url,
                    fileName: fileItem.fileName || fileItem.name,
                    fileType: this.getFileType(key), // 根据字段名判断文件类型
                    // 其他附件字段...
                });
            });
        }
    });

    // 返回完整的数据结构
    return {
        businessDto: {
            ...businessDto,
            acceptWebDto,
            valueWebDto,
            landDetailWebDto,
            attachmentWebDtoList
        },
        customizeList: [] // 根据实际情况填充
    };
},

// 辅助方法：根据字段名获取文件类型
getFileType(fieldCode) {
    const fileTypeMap = {
        'zctp': 'ASSET_IMAGE', // 资产图片
        'qztp': 'CERTIFICATE_IMAGE', // 权证图片
        // 其他字段映射...
    };
    return fileTypeMap[fieldCode] || 'OTHER';
},

// 处理特殊字段的转换（比如将字符串数字转为数字）
formatFieldValue(value, fieldType = 'string') {
    if (value === undefined || value === null || value === '') {
        return null;
    }
    
    switch (fieldType) {
        case 'number':
            return Number(value) || 0;
        case 'boolean':
            return Boolean(value);
        default:
            return value;
    }
},

        handleUploadComplete(fieldCode, fileItem) {
            if (!this.formData[fieldCode]) {
                this.$set(this.formData, fieldCode, [])
            }
            this.formData[fieldCode].push(fileItem)
        },

        handleDeleteFile(fieldCode, idxOrItem) {
            const list = this.formData[fieldCode]
            if (!Array.isArray(list) || list.length === 0) return
            if (typeof idxOrItem === 'number') {
                list.splice(idxOrItem, 1)
                return
            }
            const index = list.findIndex((f) => f === idxOrItem || (f.token && idxOrItem.token && f.token === idxOrItem.token) || (f.fileUrl && idxOrItem.fileUrl && f.fileUrl === idxOrItem.fileUrl))
            if (index > -1) list.splice(index, 1)
        }
    }
}
</script>

<style lang="less" scoped>
.group-title {
    font-size: 15px;
    line-height: 18px;
    font-weight: 600;
    padding: 14px 0 10px;
    position: relative;
    z-index: 1;
    color: #000;
    &::after {
        content: '';
        width: 60px;
        height: 8px;
        background: linear-gradient(90deg, #3772ff 0%, rgba(245, 246, 248, 0) 100%);
        position: absolute;
        bottom: 12px;
        left: 0;
        z-index: -1;
    }
}

::v-deep .new-tabs-box {
    .van-tab {
        flex: none;
        border: 1px solid #c4ccdc;
        margin-left: 10px;
        padding: 6px 12px;
        font-size: 14px;
        height: 32px;
        color: #4c505a;
        border-radius: 4px;
    }

    .van-tabs__nav--line.van-tabs__nav--complete {
        padding-left: 12px;
    }

    .van-tab--active {
        background: #3772ff !important;
        color: #fff !important;
        border-color: #3772ff;
    }

    .van-tabs__wrap {
        position: relative;

        &::after {
            content: '';
            width: 100%;
            position: absolute;
            bottom: 0;
            left: 0;
            border-bottom: 1px solid #3772ff;
        }
    }

    .van-tabs__line {
        background-color: #fff;
        width: 5px;

        &::before {
            content: '';
            position: absolute;
            left: 50%;
            width: 5px;
            height: 5px;
            top: 2px;
            background-color: #fff;
            border-top: 1px solid #3772ff;
            border-bottom: 1px solid #3772ff;
            border-left: 1px solid #3772ff;
            border-right: 1px solid #3772ff;
            transform: rotateZ(45deg) translateX(-50%);
        }
    }
}

.asset-inventory {
    background-color: #f8faff;
}

.form-container {
    padding: 16px;
    padding-bottom: 80px;
}

.form-group {
    margin-bottom: 16px;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
}

.image-upload-group {
    padding: 16px;
    background-color: #fff;
}

.image-upload-label {
    margin-bottom: 12px;
    font-size: 14px;
    color: #333;
    display: flex;
    align-items: center;
}

.required {
    color: #f53f3f;
    margin-left: 4px;
}

.image-upload-container {
    position: relative;
}

.upload-count {
    position: absolute;
    right: 16px;
    bottom: 16px;
    font-size: 12px;
    color: #999;
}

.bottom-actions {
    padding: 16px;
    background-color: #fff;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
    z-index: 2;
}

.bottom-actions .van-button {
    width: 100%;
}
</style>
